<template>
  <div class="drawerMain">
    <div class="content">
      <div class="checkBox">注意！微信小程序官方要求安卓支付只能通过虚拟支付(米大师)，如设置其它支付方式会有违规风险</div>
      <div
        v-for="(item,index) in pay_config"
        :key="index"
        class="switchPayItem baseInfo"
      >
        <div class="title rowFlex spaceBetween columnCenter"><span>{{ item.system_type==1?'安卓支付':'IOS支付' }}</span></div>
        <el-form
          :ref="'payRef'+item.system_type"
          :model="item"
          :rules="newRules"
          label-width="120px"
          class="addPay"
        >
          <el-form-item
            label="支付方式"
            prop="pay_type"
          >
            <el-radio-group
              v-model="item.pay_type"
              @change="changePaytype(item,$event)"
            >
              <el-radio label="1">微信小程序支付</el-radio>
              <el-radio label="2">客服消息支付</el-radio>
              <el-radio
                v-if="item.system_type==1"
                label="4"
              >米大师支付</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 米大师支付 -->
          <div v-if="item.pay_type==4">
            <el-form-item
              label="OfferID(支付应用ID)"
              prop="mds_pay.offer_id"
              class="lineHeight"
            >
              <el-input
                v-model="item.mds_pay.offer_id"
                clearable
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="沙箱AppKey"
              prop="mds_pay.test_app_key"
            >
              <el-input
                v-model="item.mds_pay.test_app_key"
                clearable
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="线上AppKey"
              prop="mds_pay.app_key"
            >
              <el-input
                v-model="item.mds_pay.app_key"
                clearable
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </div>
          <!-- 微信小程序支付 -->
          <div v-if="item.pay_type==1">
            <el-form-item
              label="商户号"
              prop="mini_pay_merchantIds"
            >
              <el-select
                v-if="miniInput"
                v-model="item.mini_pay_merchantIds"
                filterable
                clearable
                placeholder="请选择"
                style="width:100%;"
                collapse-tags
                multiple
              >
                <el-option
                  v-for="(items,indexs) in merchantList"
                  :key="indexs"
                  :label="items.body"
                  :value="items.merchant_id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 客服消息支付 -->
          <div v-if="item.pay_type==2">
            <el-form-item
              label="选取客户支付公众号"
              class="lineHeight"
              prop="customer_pay.official_id"
            >
              <el-select
                v-model="item.customer_pay.official_id"
                clearable
                placeholder="请选择"
                style="width:100%;"
                @change="changeOfficial(index,$event)"
              >
                <el-option
                  v-for="(items,indexs) in payOfficialList"
                  :key="indexs"
                  :label="items.label"
                  :value="items.value.toString()"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="关联商户号"
              prop="customer_pay.merchant_ids"
            >
              <el-select
                v-model="item.customer_pay.merchant_ids"
                clearable
                placeholder="请选择"
                style="width:100%;"
                collapse-tags
                multiple
              >
                <el-option
                  v-for="(items,indexs) in item.serviceList"
                  :key="indexs"
                  :label="items.body"
                  :value="items.merchant_id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="switchPayItem baseInfo">
        <div class="title rowFlex spaceBetween columnCenter"><span>IOS支付规则设置</span></div>
        <el-form
          ref="ios_pay_rules"
          :model="ios_pay_rule"
          :rules="ios_pay_rules"
          label-width="120px"
          class="addPay"
        >

          <el-form-item
            label="支付规则"
            prop="rule_type"
          >
            <el-radio-group
              v-model="ios_pay_rule.rule_type"
              @change="onIosPayChang"
            >

              <el-radio :label="1">
                <span>规避审核支付</span>
                <el-tooltip
                  effect="dark"
                  content="首次支付需用户观看时间满5分钟且连续观看>3集"
                  placement="top"
                >
                  <i
                    class="el-icon-question"
                    style="margin-left:5px;"
                  ></i>
                </el-tooltip>
              </el-radio>
              <el-radio :label="2">
                <span>按顺序观看支付</span>
                <el-tooltip
                  effect="dark"
                  content="设置时间段内，用户需按顺序观看付费；非设置时间段内，支持直接付费"
                  placement="top"
                >
                  <i
                    class="el-icon-question"
                    style="margin-left:5px;"
                  ></i>
                </el-tooltip>
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            v-if="ios_pay_rule.rule_type == 2"
            label="按顺序观看开启时间"
            class="lineHeight"
          >
            <div class="ios_pay_time">
              <div class="ios_pay_time">
                <el-select
                  v-model="ios_pay_rule.rule[0].time_type"
                  style="width: 100px;"
                  placeholder="请选择"
                >
                  <el-option
                    label="当日"
                    :value="1"
                  >
                  </el-option>
                </el-select>
                <el-time-picker
                  v-model="ios_pay_rule.rule[0].time"
                  style="width: 100px;margin-left: 5px;"
                  placeholder="时间"
                  value-format="HH:mm"
                  format="HH:mm"
                  @change="ios_pay_rule.rule[1].time = ''"
                >
                </el-time-picker>
              </div>
              ~
              <div class="ios_pay_time">
                <el-select
                  v-model="ios_pay_rule.rule[1].time_type"
                  style="width: 100px;"
                  placeholder="请选择"
                  @change="onTimeTypeChange"
                >
                  <el-option
                    label="当日"
                    :value="1"
                  >
                  </el-option>
                  <el-option
                    label="次日"
                    :value="2"
                  >
                  </el-option></el-select>
                <el-time-picker
                  v-model="ios_pay_rule.rule[1].time"
                  style="width: 100px;margin-left: 5px;"
                  placeholder="时间"
                  value-format="HH:mm"
                  format="HH:mm"
                  @change="ontimepickerChange"
                >
                </el-time-picker>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <span class="dialog-footer rowFlex">
      <el-button
        class="btn"
        @click="close"
      >取 消</el-button>
      <el-button
        class="btn"
        type="primary"
        :loading="loading"
        @click="commitData"
      >确 定</el-button>
    </span>
  </div>
</template>

<script>
import { merchant, officeMerchantList, miniAppMerchantCheck, setPayConfig, getPayConfig } from '@/api/miniApp'
import { mapState, mapActions } from 'vuex'
export default {
  props: ['rowInfo'],
  data() {
    return {
      loading: false,
      miniInput: true,
      payOfficialList: [],
      merchantList: [],
      rules: {
        'mds_pay.offer_id': [{ required: true, message: '请设置米大师OfferID', trigger: 'blur' }],
        'mds_pay.app_key': [{ required: true, message: '请设置米大师线上app_key', trigger: 'blur' }],
        'mds_pay.test_app_key': [{ required: true, message: '请设置米大师支付沙箱key', trigger: 'blur' }],
        'customer_pay.official_id': [{ required: true, message: '请选择支付公众号', trigger: 'change' }],
        'customer_pay.merchant_ids': [{ required: true, message: '请选择关联商户号', trigger: 'change' }],
        // 新增的
        mini_pay_merchantIds: [{ required: true, message: '请选择关联商户号', trigger: 'change' }]
      },
      newRules: {},
      // 新增的的代码
      pay_config: [
        { pay_type: '1', system_type: '1', mini_pay_merchantIds: [], mds_pay: { app_key: '', offer_id: '', test_app_key: '' }, customer_pay: { merchant_ids: [], official_id: '' }, serviceList: [] },

        { pay_type: '1', system_type: '2', mini_pay_merchantIds: [], mds_pay: { app_key: '', offer_id: '', test_app_key: '' }, customer_pay: { merchant_ids: [], official_id: '' }, serviceList: [] }
      ],
      ios_pay_rule: {
        rule_type: 1,
        rule: [
          { time: '', time_type: 1 },
          { time: '', time_type: 1 }
        ]
      },
      ios_pay_rules: {
        rule_type: [{ required: true, message: '选择支付规则', trigger: 'blur' }]
      },
      radioList: [
        { label: '米大师', value: '4' },
        { label: '微信小程序支付', value: '1' },
        { label: '客服消息支付', value: '2' }
      ]
    }
  },
  created() {
    this.newRules = this.rules
  },
  async mounted() {
    this.requestMerchantList()
    this.payOfficialList = await this.requestCommonData({ type: 'payOfficial' })
    this.getPayConfig()
    const rowInfo = JSON.parse(JSON.stringify(this.rowInfo))
    this.ios_pay_rule = rowInfo.ios_pay_rule
      ? {
          rule: [
            { time: '', time_type: 1 },
            { time: '', time_type: 1 }
          ],
          ...JSON.parse(rowInfo.ios_pay_rule)
        }
      : this.ios_pay_rule
    console.log(this.rowInfo.ios_pay_rule)
  },
  methods: {
    ...mapActions('common', ['requestCommonData']),
    // 回显的时候获取客服消息的关联商户号 传值为公众号的ID
    ontimepickerChange(value) {
      if (!value || !this.ios_pay_rule.rule[0].time) {
        return
      }
      const arr1 = this.ios_pay_rule.rule[0].time.split(':')
      const arr2 = value.split(':')
      if (this.ios_pay_rule.rule[1].time_type == 1) {
        console.log(arr1, arr2)
        if (arr1.length > 0 && arr2.length > 0) {
          if (arr1[0] * 1 > arr2[0] * 1) {
            this.$message.error('当日结束时间不可大于当时起始时间')
            this.ios_pay_rule.rule[1].time = ''
          } else if (arr1[1] * 1 > arr2[1] * 1) {
            this.$message.error('当日结束时间不可大于当时起始时间')
            this.ios_pay_rule.rule[1].time = ''
          }
        }
      }
    },
    onTimeTypeChange() {
      this.ios_pay_rule.rule[1].time = ''
    },
    onIosPayChang(value) {
      console.log(value)
      if (value == 2) {
        this.ios_pay_rule = {
          rule_type: 2,
          rule: [
            { time: '', time_type: 1 },
            { time: '', time_type: 1 }
          ]
        }
      }
    },
    selectOfficial(value) {
      return new Promise((resolve, reject) => {
        officeMerchantList({ official_id: value }).then((res) => {
          resolve(res.data)
        })
      })
    },
    changePaytype(item, value) {
      this.newRules = {}
      setTimeout(() => {
        this.newRules = this.rules
      }, 100)
      if (value == 1) {
        this.miniInput = false
        setTimeout(() => {
          this.miniInput = true
        }, 100)
      }
    },
    async changeOfficial(index, value) {
      const serviceList = await this.selectOfficial(value)
      this.$set(this.pay_config[index], 'serviceList', serviceList)
    },
    async getPayConfig() {
      const data = {
        mini_app_id: this.rowInfo.id
      }
      const res = await getPayConfig(data)
      if (res.data.length > 0) {
        this.pay_config = res.data
        if (this.pay_config[0] && this.pay_config[0].customer_pay.official_id && this.pay_config[0].customer_pay.official_id !== '') {
          const serviceList = await this.selectOfficial(this.pay_config[0].customer_pay.official_id)
          this.$set(this.pay_config[0], 'serviceList', serviceList)
        } else {
          this.$set(this.pay_config[0], 'serviceList', this.merchantList)
        }
        if (this.pay_config[1] && this.pay_config[1].customer_pay.official_id && this.pay_config[1].customer_pay.official_id !== '') {
          const serviceList = await this.selectOfficial(this.pay_config[1].customer_pay.official_id)
          this.$set(this.pay_config[1], 'serviceList', serviceList)
        } else {
          this.$set(this.pay_config[1], 'serviceList', this.merchantList)
        }
      } else {
        // this.$set(this.pay_config[0], 'serviceList', this.merchantList)
        // this.$set(this.pay_config[1], 'serviceList', this.merchantList)
      }
      this.pay_config.map((item) => {
        if (!item.customer_pay.official_id) {
          item.customer_pay = { merchant_ids: [], official_id: '' }
        }
        if (!item.mds_pay.app_key) {
          item.mds_pay = { app_key: '', offer_id: '', test_app_key: '' }
        }
      })
    },
    close() {
      this.$emit('cancel')
    },
    commitData() {
      const params = this.pay_config.map((item) => {
        let handleObj = {}
        if (item.pay_type == 1) {
          handleObj = {
            pay_type: item.pay_type || '',
            system_type: item.system_type || '',
            merchant_ids: item.mini_pay_merchantIds
          }
        } else if (item.pay_type == 2) {
          handleObj = {
            pay_type: item.pay_type || '',
            system_type: item.system_type || '',
            merchant_ids: item.customer_pay.merchant_ids,
            official_id: item.customer_pay.official_id
          }
        } else if (item.pay_type == 4) {
          handleObj = {
            pay_type: item.pay_type || '',
            system_type: item.system_type || '',
            app_key: item.mds_pay.app_key,
            offer_id: item.mds_pay.offer_id,
            test_app_key: item.mds_pay.test_app_key
          }
        } else {
          return {}
        }
        return handleObj
      })

      let isSubmit = true
      this.$refs.payRef1[0].validate((valid) => {
        if (valid) {
          isSubmit = true
        } else {
          isSubmit = false
        }
      })
      this.$refs.payRef2[0].validate((valid) => {
        if (valid) {
          isSubmit = true
        } else {
          isSubmit = false
        }
      })
      this.$refs.ios_pay_rules.validate((valid) => {
        if (valid) {
          isSubmit = true
        } else {
          isSubmit = false
        }
      })
      if (this.ios_pay_rule.rule_type == 2) {
        if (!this.ios_pay_rule.rule[0].time || !this.ios_pay_rule.rule[1].time) {
          this.$message.error('请输入时间')
          isSubmit = false
        }
      }

      if (isSubmit) {
        this.inspect(params)
      }
    },
    async inspect(params) {
      let merchant_id = []
      let payType = 0
      this.pay_config.map((item) => {
        if (item.pay_type == 1) {
          payType = 1
          merchant_id = merchant_id.concat(item.mini_pay_merchantIds)
        }
      })
      const data = {
        merchant_id: merchant_id,
        mini_app_id: this.rowInfo.id
      }
      const res = await miniAppMerchantCheck(data)
      if (res.status_code != 1) {
        return
      }
      console.log(this.activeTab)
      if (payType == 1 && res.data.is_show == 1) {
        const h = this.$createElement
        this.$msgbox({
          title: '提示',
          message: h('p', null, [h('div', null, `${res.data.msg}`), h('span', { style: 'color: #b3b3b3; font-size:12px' }, '注意：检测数据非实时，每天01:00更新')]),
          showCancelButton: true,
          confirmButtonText: '确定已关联',
          cancelButtonText: '取消'
        })
          .then((action) => {
            this.submit(params)
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.submit(params)
      }
    },
    submit(params) {
      this.loading = true
      const data = {
        mini_app_id: this.rowInfo.id,
        pay_config: params,
        ios_pay_rule: this.ios_pay_rule.rule_type == 1 ? { rule_type: this.ios_pay_rule.rule_type } : this.ios_pay_rule
      }
      setPayConfig(data).then(
        (res) => {
          this.loading = false
          if (res.status_code === 1) {
            this.close()
            this.$emit('ok')
          }
        },
        (err) => {
          this.loading = false
        }
      )
    },
    // 小程序支付的时候的商户号下拉
    requestMerchantList() {
      merchant({ mini_app_id: this.rowInfo.id }).then((res) => {
        if (res.data.data) {
          res.data.data.map((item) => {
            item.label = item.body + '-' + item.merchant_id
            item.value = item.merchant_id
          })
          this.merchantList = res.data.data
        }
      })
    }
  }
}
</script>

  <style lang="scss" scoped>
.serviceMessage {
  width: 630px;
  padding-top: 10px;
}
.drawerMain {
  width: 670px;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  padding-bottom: 30px;
}
.content {
  width: 650px;
  padding: 20px;
}
.switchPayItem {
  width: 100%;
  margin-top: 20px;
  height: auto;
  border: 1px solid #f1f5fd;
  border-radius: 5px;
  .title {
    width: 100%;
    height: 40px;
    background: #f7f8fa;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
  }
}
.checkBox {
  width: 100%;
  height: auto;
  background: #fdf6ec;
  border-radius: 4px;
  border: 1px solid #f2bc69;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #e6a23c;
  padding: 10px;
  margin-bottom: 20px;
}
.addPay {
  width: 600px;
  padding-top: 10px;
  padding: 0 20px;
}
.dialog-footer {
  width: calc(100% - 20px);
  z-index: 1000;
}
.ios_pay_time {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>